<template>
    <div>
        <div>
            <div class="student-top" style="background-color:white;">
                <span>
                    <div class="student-logo">
                        <img border="0" @click="home" src="https://www.ketangpai.com/images/common/logo_blue.png" width="128" height="32" align="top"/>
                    </div>
                    <a @click="returnCourse" target="_self" style="color:black;margin-left: 30px;font-weight: bold;">我的课堂&nbsp;&nbsp;</a>
                    <span style="margin-right:530px;">> &nbsp;成员</span>
                    <a href="" target="_self" class="one">Ai工作集</a>
                    <a href="" target="_self" class="one">
                        <span class="iconfont">&#xe620;</span>
                        论文查重
                    </a>
                    <a href="" target="_self" class="one">
                        <span class="iconfont">&#xe6aa;</span>
                        任务管理
                    </a>
                     <button style="border:none;position: absolute;top: 28px;background-color: white;">
                        <span class="iconfont" style=" font-size:23px;padding-top: 0px;">&#xe668;</span>
                    </button>
                    <el-dropdown  trigger="click" style="margin-left: 30px;">
                          <el-avatar :size="40" style="margin-left: 20px;position: absolute;top :15.5px" icon="el-icon-user-solid" ></el-avatar>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item>
                                <span class="iconfont">&#xe674;</span>
                                开通VIP
                            </el-dropdown-item>
                            <el-dropdown-item> 
                                <span class="iconfont">&#xe611;</span>
                                机构用户认证
                            </el-dropdown-item>
                            <el-dropdown-item @click="person">
                                <span class="iconfont">&#xe656;</span>
                                个人设置
                            </el-dropdown-item>
                            <el-dropdown-item @click="returnLogin">
                                <span class="iconfont">&#xe60a;</span>
                                退出登录
                            </el-dropdown-item>
                          </el-dropdown-menu>
                            
                        </template>
                    </el-dropdown>
                </span>
            </div>
            <hr/>
        </div>
        <div>
            <div style="float: right; margin-bottom: 10px;padding: 10px 140px;">
                <el-input 
                    placeholder="请输入学号姓名"
                    type="text"
                    style="width: 300px;"
                    suffix-icon="SearchIcon">
                </el-input>
            </div>
            <div style="clear: both;"></div>
            <div style="padding: 10px; margin: 10px 120px; ">
                <div style="height: 500px; border: 1px solid #d2d2d2; margin-bottom: 10px;width: 250px;margin-right: 20px;border-radius: 10px;float: left;">
                    <div style="padding: 10px 20px;">
                        <span @click="allMemberVisible = true; studentVisible = false" style="margin-right: 80px; cursor: pointer;" :style="{ color: allMemberVisible ? '#4285f2' : 'black' }">全部成员</span>
                        <span @click="allMemberVisible = false; studentVisible = true" style="cursor: pointer;" :style="{ color: studentVisible ? '#4285f2' : 'black' }">学生分组</span>
                    </div>
                    <div>
                        <div v-if="allMemberVisible">
                            <div @click="teacherVisible = true; studentMemberVisible = false" style="padding: 10px 30px; font-size: 14px; font-weight: bold;" :class="{ activeStyle: teacherVisible }">教学团队</div>
                            <div @click="teacherVisible = false; studentMemberVisible = true" style="padding: 10px 30px; font-size: 14px; font-weight: bold;" :class="{ activeStyle: studentMemberVisible }">学生成员</div>
                        </div>
                    </div>
                </div>
                <div v-if="teacherVisible" style="border: 1px solid #d2d2d2; border-radius: 10px; float: left; width: 780px; padding: 25px 20px;">
                    <div>
                        <span style="font-size: larger; font-weight: bold;">教师团队</span>
                        <span style="font-size: small; margin-left: 10px;">共{{ teachers.length }}人</span>
                        <el-button v-if="type==1" type="primary" style="float: inline-end;" @click="addTeacherVisible=true">+添加助教/老师</el-button>
                        <el-dialog
                            v-model="addTeacherVisible"
                            title="添加教学团队"
                            width="700"
                            draggable
                            overflow
                        >
                        <span>将要添加的账号复制到这</span>
                        <br/>
                        <br/>
                        <el-input v-model="this.addAccount"></el-input>
                        <br/>
                        <br/>
                        <el-button style="margin-left: 535px;" @click="teacherVisible=false">取消</el-button>
                        <el-button type="primary"  @click="addTeacher">确定</el-button>
                        </el-dialog>
                    </div>
                    <div style="margin-top: 30px;">
                        <el-table
                            ref="multipleTableRef"
                            :data="teachers"
                            style="width: 100%"
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" :selectable="selectable" width="55" />
                            <el-table-column label="全部成员" property="name" width="200" />
                            <el-table-column property="account" label="账号" width="250" />
                            <el-table-column label="身份" property="role" />
                        </el-table>
                        <br/>
                        <div class="demo-pagination-block">
                            <el-pagination
                                v-model:currentPage="currentPage"
                                v-model:pageSize="pageSize"
                                :page-sizes="[1, 5, 10]"
                                layout="sizes, prev, pager, next, jumper"
                                :total="0"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                pager-text="前往"
                                page-size-text="条/页"
                            />
                        </div>
                    </div>
                </div>
                <div v-if="studentMemberVisible" style="border: 1px solid #d2d2d2; border-radius: 10px; float: left; width: 780px; padding: 25px 20px;">
                    <div>
                        <span style="font-size: larger; font-weight: bold;">全部学生</span>
                        <span style="font-size: small; margin-left: 10px;">共{{ students.length }}人</span>
                    </div>
                    <div style="margin-top: 30px;" v-if="type!=1" >
                        <el-table
                            ref="multipleTableRef"
                            :data="students"
                            style="width: 100%"
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" :selectable="selectable" width="55" />
                            <el-table-column label="全部成员" property="name" width="100" />
                            <el-table-column label="学号" property="no" width="200"/>
                            <el-table-column property="account" label="账号" width="100" />
                            <el-table-column label="加入时间" property="enterTime" />

                        </el-table>
                        <br/>
                        <div class="demo-pagination-block">
                            <el-pagination
                                v-model:currentPage="currentStudentPage"
                                v-model:pageSize="pageSize"
                                :page-sizes="[1, 5, 10]"
                                layout="sizes, prev, pager, next, jumper"
                                :total="0"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                pager-text="前往"
                                page-size-text="条/页"
                            />
                        </div>
                    </div>
                    <div style="margin-top: 30px;" v-if="type==1" >
                        <el-table
                            ref="multipleTableRef"
                            :data="students"
                            style="width: 100%"
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" :selectable="selectable" width="55" />
                            <el-table-column label="全部成员" property="name" width="100" />
                            <el-table-column label="学号" property="no" width="200"/>
                            <el-table-column property="account" label="账号" width="100" />
                            <el-table-column label="加入时间" property="enterTime" />
                            <el-table-column  label="删除成员" ><template #default="{ row }">
          <span style="cursor: pointer; color: cornflowerblue;" @click="openDeleteForm(row.id)">删除</span>
        </template></el-table-column>

                        </el-table>
                        <br/>
                        <div class="demo-pagination-block">
                            <el-pagination
                                v-model:currentPage="currentStudentPage"
                                v-model:pageSize="pageSize"
                                :page-sizes="[1, 5, 10]"
                                layout="sizes, prev, pager, next, jumper"
                                :total="0"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                pager-text="前往"
                                page-size-text="条/页"
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { useRouter } from 'vue-router';
import { ref, onMounted } from 'vue';
import Storage from '../../utils/storage.js';
import { post } from '../../utils/request';
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
    name: 'MemberPage',
    setup() {
        const router = useRouter();
        const user = Storage.getSession("user");
        const isElementVisible = ref(false);
        const allMemberVisible = ref(true);
        const studentVisible = ref(false);
        const studentMemberVisible = ref(false);
        const teacherVisible = ref(true);
        let addTeacherVisible = ref(false);
        const teachers = ref([]);
        const type = ref(0);
        const students = ref([]);
        const currentPage = ref(1);
        const currentStudentPage = ref(1);
        const pageSize = ref(10);
        const addAccount = ref();
        const currentCourse = Storage.getSession("currentCourseMember");

        const show = () => {
            isElementVisible.value = !isElementVisible.value;
        };
        //获取当前课程中用户的身份
        const getUserType = async () => {
            try {
                const response = await post('/userCourse/getUserType', { userId: user.id, courseId: currentCourse.id });
                console.log(response.data.type);
                type.value = response.data.type;
            } catch (e) {
                console.log(e);
            }
        }
        const returnCourse = () => {
            Storage.removeSession("courseSetting");
            router.push('/teacherPage');
        };

        const returnLogin = () => {
            ElMessageBox.confirm(
                '确定要退出登录？',
                'Warning',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    try {
                        Storage.removeSession("user");
                        router.push('/login');
                        ElMessage({
                            type: 'success',
                            message: '退出成功',
                        })
                    } catch (e) {
                        console.log(e);
                    }
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消操作',
                    })
                });

        };

        const getTeachers = async () => {
            try {
                console.log(currentCourse.id);
                const response = await post('/userCourse/getTeachers', currentCourse.id);
                console.log(response);
                teachers.value = response.data.map(teacher => ({
                    ...teacher,
                    role: '管理员' // 设置默认角色
                }));
            } catch (e) {
                console.error('获取教师团队失败:', e);
            }
        };
        const convertDate = (param) => {
            const date = new Date(param);
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };
        const getStudents = async () => {
            try {
                const response = await post('/userCourse/getStudents', currentCourse.id);
                console.log(response);
                students.value = response.data;
                students.value.map(student => {
                    // console.log(student);
                    if (student.enterTime != null) {
                        student.enterTime = convertDate(student.enterTime)
                    }
                })
            } catch (e) {
                console.log(e);
            }
        }

        const handleSelectionChange = (selection) => {
            console.log("选中的行:", selection);
        };

        const handleSizeChange = (val) => {
            console.log(`${val} items per page`);
        };

        const handleCurrentChange = (val) => {
            console.log(`current page: ${val}`);
        };

        const selectable = (row, index) => {
            console.log(row, index)
            return true; // 默认所有行都可以被选择
        };

        const addTeacher = async () => {
            try {
                const response = await post('/userCourse/addMember', {
                    account: addAccount.value,
                    courseId: currentCourse.id
                })
                console.log(response);
                getStudents();
                getTeachers();
                addTeacherVisible.value = false;

            } catch (e) {
                console.log(e);
            }
        }
        const person = () => {
            router.push("/userSetting")
        };
        const deleteStudent = async (userId) => {

            try {
                console.log(userId)
                const response = await post('/userCourse/deleteStudent', { userId: userId, courseId: currentCourse.id });
                console.log(response);

            } catch (e) {
                console.log(e);
            }
        };
        const openDeleteForm = (id) => {
            console.log(id);
            ElMessageBox.confirm(
                '是否要删除该学生？',
                'Warning',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    try {
                        deleteStudent(id);
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                    } catch (e) {
                        console.log(e);
                    }
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消操作',
                    })
                })
        };
        onMounted(() => {
            getTeachers();
            getStudents();
            getUserType();
            console.log(type.value);
            console.log(type.value != 1)
        });
        return {
            returnCourse,
            returnLogin,
            show,
            addAccount,
            isElementVisible,
            allMemberVisible,
            studentVisible,
            studentMemberVisible,
            teacherVisible,
            teachers,
            currentPage,
            pageSize,
            handleSelectionChange,
            handleSizeChange,
            handleCurrentChange,
            selectable,
            students,
            currentStudentPage,
            getStudents,
            convertDate,
            addTeacherVisible,
            addTeacher,
            user,
            person,
            getUserType,
            type,
            deleteStudent,
            openDeleteForm
        };
    }
};
</script>
<style>
.activeStyle{
    background-color: #e8f0ff;
    color: black;
}
</style>